package com.itheima.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.store.CatalogDao;
import com.itheima.domain.store.Catalog;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.CatalogService;
import com.itheima.utils.UUIDUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class CatalogServiceImpl implements CatalogService {
    @Override
    public PageInfo<Catalog> queryPage(Integer pageNum, Integer pageSize) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);

        PageHelper.startPage(pageNum,pageSize);
        List<Catalog> list = catalogDao.findAll();
        PageInfo<Catalog> pageInfo = new PageInfo<>(list);

        sqlSession.close();
        return pageInfo;
    }

    @Override
    public List<Catalog> findAll() throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);

        List<Catalog> list = catalogDao.findAll();

        sqlSession.close();
        return list;
    }

    @Override
    public Catalog findById(String id) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);

        Catalog catalog = catalogDao.findById(id);

        sqlSession.close();
        return catalog;
    }

    @Override
    public void save(Catalog catalog) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);


        catalog.setId(UUIDUtil.getSimpleUUID());
        catalog.setCreateTime(new Date());
        catalogDao.save(catalog);

        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void update(Catalog catalog) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);

        catalogDao.update(catalog);

        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void deleteById(String... ids) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CatalogDao catalogDao = sqlSession.getMapper(CatalogDao.class);

        for (String id : ids) {
            catalogDao.deleteById(id);
        }

        sqlSession.commit();
        sqlSession.close();

    }
}
